﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data;
using System.Data.Entity;

using Domain;

namespace ExcelUploadPoc.Controllers {
  public class HomeController : Controller {
    private EFDbContext db = new EFDbContext();

    public ActionResult Index() {
      ViewBag.Message = "Upload an Excel file";

      return View();
    }

    public ActionResult UploadSuccessful() {
      ViewBag.Message = "Upload succeeded";

      return View();
    }

    public ActionResult UploadFout() {
      ViewBag.Message = "Upload Fout";
      return View();
    }

    public ActionResult UploadFail() {
      ViewBag.Message = "Upload failed";

      return View();
    }
    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file) {
      bool valid = false;
      if (file != null && file.ContentLength > 0 && file.ContentType == "application/vnd.ms-excel") { //only allow csv files
        string path = Path.Combine(Server.MapPath("~/Upload"), file.FileName);
        file.SaveAs(path);
        CSVFileChecker checker = CSVFileChecker.GetInstance(path);
        valid = checker.CheckFileHeading();
        
        string line;
        using (StreamReader r = new StreamReader(path)) {
          r.ReadLine();
          while ((line = r.ReadLine()) != null) {
            if (ModelState.IsValid) {
              string[] values = line.Split(';');
              Student s = new Student();
              s.StudentId = Int32.Parse(values[0]);
              s.Name = values[1];

              db.Students.Add(s);
              db.SaveChanges();
            }     
          }
        }

        checker.FinishParsing();
        if (valid) return RedirectToAction("UploadSuccessful");
        else return RedirectToAction("UploadFail");
      }     
      return RedirectToAction("Index");
    }

    public ActionResult About() {
      return View();
    }
  }
}


/* // Verify that the user selected a file

      if (file != null && file.ContentLength > 0 && file.ContentType == "application/vnd.ms-excel") { //only allow csv files
       /* // extract only the filename
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/UploadData"), fileName);
        file.SaveAs(path); 


     
        
     
      }
      else {
        // redirect back to the index action to show the form once again
     
      }*/